package com.fanvil.videoconference;

import android.opengl.GLES11Ext;
import android.opengl.GLES20;

import com.fanvil.videoconference.FvlLogger;

public class FvlTextureSource {

    private static FvlLogger sLogger =
        FvlLogger.getLogger(FvlTextureSource.class.getSimpleName(), FvlLogger.DEBUG);

    private int mTexId;
    private int mTarget;
    private boolean mIsOwner;
    private int mVboId;

    public static FvlTextureSource newExternalTexture() {
        sLogger.d("newExternalTexture");
        return new FvlTextureSource(FvlGLToolbox.generateTexture(),
                                 GLES11Ext.GL_TEXTURE_EXTERNAL_OES,
                                 true);
    }

    public int getTextureId() {
        sLogger.d("getTextureId: mTexId=" + mTexId);
        return mTexId;
    }

    public int getVboId() {
        sLogger.d("getVboId: mVboId=" + mVboId);
        return mVboId;
    }

    public int getTarget() {
        sLogger.d("getTarget: mTarget=" + mTarget);
        return mTarget;
    }

    public void bind() {
        sLogger.d("bind: mTarget=" + mTarget + " mTexId=" + mTexId);
        GLES20.glBindTexture(mTarget, mTexId);
        FvlGLToolbox.checkGlError("glBindTexture");
    }

    public void setParameteri(int parameter, int value) {
        sLogger.d("setParameteri: parameter=" + parameter + " value=" + value);
        GLES20.glTexParameteri(mTarget, parameter, value);
    }

    public void setParameterf(int parameter, int value) {
        sLogger.d("setParameterf: parameter=" + parameter + " value=" + value);
        GLES20.glTexParameterf(mTarget, parameter, value);
    }

    public void release() {
        sLogger.d("release");
        if (FvlGLToolbox.isTexture(mTexId) && mIsOwner) {
            FvlGLToolbox.deleteTexture(mTexId);
        }
        mTexId = FvlGLToolbox.textureNone();
    }

    @Override
    public String toString() {
        return "FvlTextureSource(id=" + mTexId + ", target=" + mTarget + ")";
    }

    private FvlTextureSource(int texId, int target, boolean isOwner) {
        sLogger.d("FvlTextureSource: texId=" + texId + " target=" + target + " isOwner=" + isOwner);
        mTexId = texId;
        mTarget = target;
        mIsOwner = isOwner;
        mVboId = FvlGLToolbox.generateVbo();
    }
}

